package com.lcj.hub.common;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lcj.hub.common.constant.ErrorCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {

    private String code;

    private String msg;

    private T data;

    private static final Gson gson = new GsonBuilder().serializeNulls().create();


    // 执行成功
    public static <T> Result<T> success(T data) {
        return new Result<>(ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMessage(), data);
    }

    // 执行失败
    public static Result<String> failed(String msg) {
        return failed(ErrorCode.ERROR, msg, "");
    }

    // 执行失败
    public static Result<String> failed(ErrorCode error) {
        return new Result<>(error.getCode(), error.getMessage(), "");
    }

    // 传入错误码的方法
    public static Result<String> failed(ErrorCode error, String msg) {
        return failed(error, msg, "");
    }

    // 传入错误码的数据
    public static <T> Result<T> failed(ErrorCode error, String msg, T data) {
        msg = StringUtils.isEmpty(msg) ? error.getMessage() : msg;
        return new Result<>(error.getCode(), msg, data);
    }

    public String toJsonString() {
        try {
            return gson.toJson(this);
        } catch (Exception e) {
            ErrorCode error = ErrorCode.ERROR;
            return """
                    {
                        "code": "%s",
                        "msg": "%s",
                        "data": "%s"
                    }
                    """.formatted(error.getCode(), error.getMessage(), "");
        }
    }
}